// pages/chat/chat.js
let app = getApp();
const util = require('../../utils/util.js');
const recorderManager = wx.getRecorderManager();
const innerAudioContext = wx.createInnerAudioContext();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    callContent: [
      // {
      //   user: 'teller',
      //   voiceSrc: '',
      //   answer: '广东广州'
      // },
      // {
      //   user: 'customer',
      //   voiceSrc: '',
      //   duration: 6000,
      //   voiceText: '是的'
      // }
    ],
    scrollTop: 0,
    callStatus: '按住 说话',
    tellerAudio1: '../images/voice2.png',
    tellerAudio2: '../images/voice2.gif',
    meAudio1: '../images/voice1.png',
    meAudio2: '../images/voice1.gif',
    currentUser: {},
    curAudioIndex: 0,
    isOver: false
  },
  // 播放语音事件
  bindPlayVoice: function(e) {
    console.log('播放事件e：', e);
    var index = e.currentTarget.dataset.index,
      role = e.currentTarget.dataset.role,
      voiceSrc = e.currentTarget.dataset.voicesrc;

    this.setData({
      curAudioIndex: index
    });
    this.playVoice(role, voiceSrc);
  },
  // 播放语音
  playVoice: function(role, voiceSrc, isFirst) {
    var that = this;
    console.log(voiceSrc);

    // 本地音频不需要下载
    if (role == 'teller' && isFirst) {
      wx.downloadFile({
        url: voiceSrc,
        success: function (res) {
          innerAudioContext.src = res.tempFilePath;         
        },
      });
    } else {
      innerAudioContext.src = voiceSrc;
    }
  },

  // 挂断通话
  releaseCall: function() {
    wx.getStorage({
      key: 'verifyInfo',
      success: function(res) {
        wx.redirectTo({
          url: '/pages/verifyInfo/verifyInfo',
        })
      },
      fail: function() {
        console.log('读取验证信息失败');
        wx.redirectTo({
          url: '/pages/index/index',
        })
      }
    })

    this.setData({
      isOver: false
    });
  },

  // 音频录制 
  beginCall: function() {
    var that = this;
    this.setData({
      callStatus: '松开 结束'
    });

    wx.showToast({
      title: '录音中',
      icon: 'none',
      image: '../images/record.png',
      duration: 600000
    });

    recorderManager.onStart(() => {
      console.log('recorder start')
    })

    recorderManager.onStop((res) => {
      console.log('recorder stop', res)
      // 客户的语音显示
      const {
        tempFilePath,
        duration
      } = res

      var {
        callContent
      } = this.data;

      var newData = {
        user: 'customer',
        voiceSrc: tempFilePath,
        audioPlaying: false,
        voiceText: '',
        duration: util.formateSecond(duration)
      };

      callContent.push(newData);

      this.setData({
        callContent: callContent,
        scrollTop: this.data.scrollTop + 50
      });

      let userid = '';
      wx.getStorage({
        key: 'userid',
        success: function(res) {
          userid = res.data;
          // console.log('chat userId:', userid);
          // 发送录音文件到后台服务器
          wx.showLoading({
            title: '加载中',
          });
          wx.uploadFile({
            url: app.globalData.baseUrl + '/chat',
            filePath: tempFilePath,
            dataType: 'json',
            name: 'file',
            formData: {
              userid: userid
            },
            header: {
              'content-type': 'multipart/form-data'
            },
            success: function(res) {
              if (res.data == '' || res.data == undefined) {
                return false;
              }

              if (typeof res.data == 'string') {
                try {
                  res.data = JSON.parse(res.data);
                } catch(err) {
                  setTimeout(function(){
                    wx.showToast({
                      title: '请求失败，请重新回答',
                      icon: 'none',
                      duration: 3000
                    })
                  }, 1000);
                  
                }                
              }
              console.log('返回信息：', res.data);
              console.log('识别文本:', res.data.text);

              if (res.data.status) {
                var tellerSrc = res.data.osslink;
                // 返回的客服回答填充到对话中
                var {
                  callContent
                } = that.data;

                callContent[callContent.length - 1].voiceText = res.data.text;

                var newData = {
                  user: 'teller',
                  audioPlaying: false,
                  voiceSrc: tellerSrc,
                  answer: res.data.answer,
                  isLoading: false
                  // duration: duration
                };

                callContent.push(newData);

                that.setData({
                  callContent: callContent,
                  scrollTop: that.data.scrollTop + 50
                });

                if (res.data.verifyInfo) {
                  wx.setStorage({
                    key: 'verifyInfo',
                    data: res.data
                  });
                }

                if (res.data.Hangup && res.data.Hangup == 'yes') {
                  that.setData({
                    isOver: true
                  });
                }

                var index = callContent.length - 1,
                  role = 'teller',
                  voiceSrc = tellerSrc;

                console.log('callback tellerSrc:', tellerSrc);

                that.setData({
                  curAudioIndex: index
                });
                that.playVoice(role, voiceSrc, true);
              }

            },
            fail: function(error) {
              console.log('chating fail: ', error.errMsg);              
            },
            complete: function() {
              wx.hideLoading();
            }
          });
        },
      })


    })

    recorderManager.onFrameRecorded((res) => {
      const {
        frameBuffer
      } = res
      console.log('frameBuffer.byteLength', frameBuffer.byteLength)
    })

    const options = {
      audioSource: 'auto',
      duration: 600000,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 48000,
      format: 'mp3',
      // frameSize: 50
    }

    recorderManager.start(options);

  },
  // 结束录制
  endCall: function() {
    const that = this;
    that.setData({
      callStatus: '按住 说话'
    });
    wx.hideToast();
    recorderManager.stop();

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const that = this;

    wx.getStorage({
      key: 'callUser',
      success: function(res) {
        that.setData({
          currentUser: res.data
        });
      },
    });

    var {
      callContent
    } = that.data;

    var callVoice = '';
    wx.getStorage({
      key: 'curUserAudio',
      success: function(res) {
        callVoice = res.data.osslink;

        var newData = {
          user: 'teller',
          audioPlaying: false,
          voiceSrc: callVoice,
          answer: res.data.answer,
          isLoading: false
          // duration: duration
        };

        callContent.push(newData);

        that.setData({
          callContent: callContent
        });

        var index = 0,
          role = 'teller',
          voiceSrc = callVoice;
        that.setData({
          curAudioIndex: index
        });
        that.playVoice(role, voiceSrc, true);
      },
    })



    innerAudioContext.obeyMuteSwitch = false;
    innerAudioContext.autoplay = true;
    // 音频播放事件
    innerAudioContext.onPlay(() => {
      console.log('开始播放');

      const {
        callContent,
        curAudioIndex
      } = that.data;

      callContent.forEach(function(item){
        item.audioPlaying = false;
      });

      callContent[curAudioIndex].audioPlaying = true;

      that.setData({
        callContent: callContent
      });
    });

    // 音频加载中事件，当音频因为数据不足，需要停下来加载时会触发
    innerAudioContext.onWaiting(() => {
      // const { callContent } = that.data;

      // if (role == 'teller') {
      //   callContent[index].isLoading = true;
      //   that.setData({
      //     callContent: callContent
      //   });
      // }
    });

    // 音频播放进度更新事件
    innerAudioContext.onTimeUpdate(() => {
      recorderManager.onStart(() => {
        console.log('recorder start2')
        innerAudioContext.stop();
      })
    });

    // 音频停止事件
    innerAudioContext.onStop(() => {
      console.log('中途停止播放')

      const {
        callContent,
        curAudioIndex
      } = that.data;


      callContent[curAudioIndex].audioPlaying = false;

      that.setData({
        callContent: callContent
      });

    });

    // 音频自然播放结束事件
    innerAudioContext.onEnded(() => {
      console.log('停止播放')

      const {
        callContent,
        curAudioIndex
      } = that.data;

      callContent[curAudioIndex].audioPlaying = false;

      that.setData({
        callContent: callContent
      });

    });

    innerAudioContext.onError(() => {

    });

  },

  onHide: function () {
    innerAudioContext.src = '';
    innerAudioContext.stop();
  },

  onUnload: function () {
    innerAudioContext.src = '';
    innerAudioContext.stop();
  }

})